package com.example.demo.shiro;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    @Bean
    public ConsumerRealm consumerRealm() {
        ConsumerRealm consumerRealm = new ConsumerRealm();
        return consumerRealm;
    }

    //权限管理，配置主要是Realm的管理认证
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(consumerRealm());
        return securityManager;
    }

    //Filter工厂，设置对应的过滤条件和跳转条件
    @Bean
    public ShiroFilterFactoryBean shiroFiler(SecurityManager securityManager){
        ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean();
//        bean.setFilters();
        bean.setSecurityManager(securityManager);
        //自定义filter
        Map<String,Filter> filterMap=new LinkedHashMap<>();
        filterMap.put("consumeFilter",new ConsumeFilter());
        bean.setFilters(filterMap);
        //没有登陆的用户只能访问登陆页面
        bean.setLoginUrl("/User/noLogin");
        //登录成功的url
        //bean.setSuccessUrl("/home");
        //未授权跳转的url
        bean.setUnauthorizedUrl("/User/error");
        //配置访问权限
        LinkedHashMap<String, String> filterChainDefinitionMap=new LinkedHashMap<>();
        filterChainDefinitionMap.put("/User/index", "anon");
        filterChainDefinitionMap.put("/Login/login", "anon");//不需要验证
        filterChainDefinitionMap.put("/User/*", "consumeFilter");//需要权限
        bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return bean;
    }

}
